<?php
/*
$mutex = Mutex::create();
if($mutex){
   exit;
   Mutex::destroy($mutex);	
}*/

if ( !defined("SCRIPT_DIR") ) {
	define("SCRIPT_DIR", dirname(__FILE__));
}

$path = explode('/',__FILE__);
if ( !defined("FILE") ) {
	define("FILE",end($path));
}

function path_format($file) {
	return SCRIPT_DIR . '/' . $file;
}
include_once(path_format('logger.php'));
include_once(path_format('config.php'));
include_once(path_format('mysql.php'));
include_once(path_format('redis.php'));

function sync() {
	$preTenMinTime = 0;
	while(1)
	{
		$now = time();
		//$curTenMinTime = (int) ($now/600) * 600;
		//if ($curTenMinTime > $preTenMinTime)
		//{
			//$preTenMinTime = $curTenMinTime;
			//do some on time thing
			//连接数据库
			$mysql = new MysqlDriver();
			$ret = $mysql->connect(Config::$mysql_config);
			if ( !$ret ) {
				Config::$log->error(FILE, "connect mysql error.");
			}
			//连接redis			
			$redis = new RedisDriver();
			$ret = $redis->initDataRedis(5);
			if (!$ret){
				Config::$log->error(FILE, "initCacheRedis error");
			}
			
	    	//玩家每盘游戏金币记录
			$keys = $redis->data_redis->keys("rec:*");	
			
			
		    $knum = count($keys);
			for($i=0;$i<$knum;$i++){	
					
			  $data = $redis->data_redis->hGetAll($keys[$i]);
			 
			  $info =array();
			  $info['type'] = $data['type'];
			  $info['vid']  = $data['vid'];
			  $info['tid']  = $data['tid'];
			  $info['seatid'] = $data['seatid'];
			  $info['uid']    = $data['uid'];
			  $info['money']  = $data['money'];
			  $info['change_money'] = $data['change_money'];
              $info['create_time']  = $data['create_time'];
			  
			  Config::$logc->info('ZjhSyncMoneychange', "userid:".$data['uid'].":".json_encode($info));
			  $result = $mysql->insert("money_change_rec",$info); 
			  $redis->data_redis->delete($keys[$i]);

			}
			
			//玩家游戏中存取款记录
			
			$bank_rec = $redis->data_redis->keys("bank_rec:*");	
		    $bnum = count($bank_rec);
			for($i=0;$i<$bnum;$i++){	
					
			  $bdata = $redis->data_redis->hGetAll($bank_rec[$i]);
			 
			  $binfo =array();
			  $binfo['type'] = 6;
			  $binfo['vid']  = 1;
			  $binfo['tid']  = 0;
			  $binfo['seatid'] = 0;
			  $binfo['uid']    = $bdata['UserID'];
			  $binfo['money']  = $bdata['MoneyInRoom'];
			  $binfo['change_money'] = $bdata['OutMoney'];
              $binfo['create_time']  = $bdata['CollectTime'];

			 
			  Config::$logc->info('ZjhSyncMoneychange', "userid:".$bdata['UserID'].":".json_encode($binfo));
			  $result = $mysql->insert("money_change_rec",$binfo); 
			  $redis->data_redis->delete($bank_rec[$i]);

			}
			
		//}
		echo date('Y:m:d H:i:s')." ZjhSyncMoneychange working...\r\n"; 	
		sleep(60);
	}
	
	
}

sync();
